import errorCodesBuilder from '../helpers/errorCodesBuilder';

const errorCodes = errorCodesBuilder();

const MODULE_MAP = {
	receiver: '告警人',
	group: '告警组',
};
export default function removeManyResolveBuilder({
	model,
	balanceOps,
	permissionRequired,
	prepareFilter = ({ args }) => args,
	module = 'receiver',
}) {
	return async (root, args, { request }) => {
		const {
			auth: {
				credentials: { permissionMap, uid },
			},
			server: {
				methods: { calcBalance },
			},
		} = request;

		const filter = prepareFilter({ args, request });
		const items = await model.find(filter);
		const status = await Promise.allSettled(
			items.map(async item => {
				const haveOtherUserPermission =
					permissionMap[`${permissionRequired}\x010`];
				if (item.uid.toString() !== uid && !haveOtherUserPermission) {
					request.log.warn({ item, uid }, '删除记录没有权限');
					return;
				}

				try {
					await item.remove();
				} catch (err) {
					const error = errorCodesBuilder[''].from(err);
					request.log.error({ error }, error.rawMessage);
					throw error;
				}

				try {
					if (balanceOps) {
						await calcBalance({ uid: item.uid, ops: balanceOps });
					}
				} catch (err) {
					const error = errorCodes[''].from(err);
					request.log.error({ error }, error.rawMessage);
					throw error;
				}

				request.log.audit(
					{
						module,
						activeType: 'delete',
						actionMessage: `更新${MODULE_MAP[module]}`,
						detail: `删除${MODULE_MAP[module]}${item.name}。`,
					},
					`新建${MODULE_MAP[module]}`
				);
			})
		);

		return { numAffected: status.filter(x => x.status === 'fulfilled').length };
	};
}
